package career_handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	"peilian-api/utils/format"
	"strings"
)

func TagCreate(c *gin.Context) {
	var cType tables.Criteria
	if err := c.ShouldBindJSON(&cType); err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	aId, exists := c.Get("aid")
	if !exists {
		format.NewResponseJson(c).Err(http.StatusUnauthorized, "无agent_id")
		return
	}
	cType.AgentId = aId.(uint)
	cType.IsBuildIn = 1
	var n int64
	variable.DB.MySQL.Model(&tables.Criteria{}).
		Where("criteria_name=? and agent_id=?", cType.CriteriaName, cType.AgentId).Count(&n)
	if n > 0 {
		format.NewResponseJson(c).Err(http.StatusBadRequest, "标签名称已经存在")
		return
	}
	if len(strings.Trim(cType.CriteriaName, " ")) == 0 {
		format.NewResponseJson(c).Err(http.StatusBadRequest, "标签名称不能为空")
		return
	}
	if err := variable.DB.MySQL.Create(&cType).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	format.NewResponseJson(c).SuccessObj(&cType)
}

func TagList(c *gin.Context) {
	aId, exists := c.Get("aid")
	if !exists {
		format.NewResponseJson(c).Err(http.StatusUnauthorized, "无agent_id")
		return
	}
	tagType := c.Query("type")
	careerTypeLi := make([]*tables.Criteria, 0)
	if err := variable.DB.MySQL.Where("agent_id in (0, ?) and type=?", aId, tagType).
		Find(&careerTypeLi).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusInternalServerError, err.Error())
		return
	}
	format.NewResponseJson(c).SuccessDataList(len(careerTypeLi), careerTypeLi)
}

func TagDelete(c *gin.Context) {
	typeId := c.Param("tagId")
	aId, exists := c.Get("aid")
	if !exists {
		format.NewResponseJson(c).Err(http.StatusUnauthorized, "无agent_id")
		return
	}
	if err := variable.DB.MySQL.Delete(&tables.Criteria{}, "id=? and agent_id=?", typeId, aId).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	format.NewResponseJson(c).SuccessObj(struct{}{})
}
